<template>
    <div id="contianer">
        <div>
            <el-form
                ref="uploadForm"
                :model="uploadForm"
                :rules="rules"
                label-width="80px"
            >
                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="课程名称" prop="folderName">
                            <el-input
                                v-model.trim="uploadForm.folderName"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="作者姓名" prop="author">
                            <el-input
                                v-model.trim="uploadForm.author"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="课程简介" prop="introduction">
                            <el-input
                                maxlength="200"
                                show-word-limit
                                v-model.trim="uploadForm.introduction"
                                type="textarea"
                                :rows="3"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <hr style="border-top: 1px solid #d8d8d8" />
                <el-row :gutter="20">
                    <el-col :span="8">
                        <h2>视频组菜单</h2>
                        <vxe-table
                            show-overflow
                            keep-source
                            ref="tableRef"
                            :row-config="{
                                keyField: 'chapter',
                                isCurrent: true,
                                isHover: true,
                            }"
                            :column-config="{ resizable: true }"
                            :print-config="{}"
                            :export-config="{}"
                            :loading="loading"
                            :tree-config="{
                                transform: false,
                                rowField: 'chapter',
                                expandAll: true
                            }"
                            :edit-config="{
                                trigger: 'click',
                                mode: 'row',
                                showStatus: true,
                            }"
                            :data="tableData"
                            @current-change="currentChangeEvent"
                        >
                            <vxe-column
                                field="chapterName"
                                title="名称"
                                tree-node
                                :edit-render="{}"
                            >
                                <template #edit="{ row }">
                                    <vxe-input
                                        v-model="row.chapterName"
                                        type="text"
                                    ></vxe-input>
                                </template>
                            </vxe-column>

                            <vxe-column type="expand" width="60" title="文件">
                                <template #content="{ row }">
                                    <ul
                                        class="expand-wrapper"
                                        v-for="(item, index) in row.videoList"
                                        :key="index"
                                    >
                                        <li
                                            style="
                                                display: flex;
                                                space-between: space-between;
                                            "
                                        >
                                            <span>{{
                                                item.videoType === 0
                                                    ? "课件："
                                                    : "视频："
                                            }}</span
                                            ><span>{{ item.fileName }}</span
                                            ><vxe-button
                                                mode="text"
                                                status="danger"
                                                @click="deleteFile(row, item)"
                                                >删除</vxe-button
                                            >
                                        </li>
                                    </ul>

                                    <!-- <el-row v-for="(item,index) in row.videoList" :key="index" type="flex">
                                        <el-col :span="4">
                                            <div class="grid-content bg-purple">
                                                {{ item.videoType === 0 ? '课件' : '视频' }}
                                            </div>
                                        </el-col>
                                        <el-col :span="8">
                                            <div class="grid-content">{{ item.fileName }}</div>
                                        </el-col>
                                        <el-col :span="4">
                                            <div class="grid-content bg-purple">{{ item.fileName }}</div>
                                        </el-col>
                                    </el-row> -->
                                </template>
                            </vxe-column>

                            <vxe-column title="操作" width="120">
                                <template #default="{ row }">
                                    <vxe-button
                                        mode="text"
                                        status="primary"
                                        @click="insertRow(row)"
                                        v-if="row.level < 3"
                                        >{{
                                            row.level === 1
                                                ? "添加章"
                                                : "添加节"
                                        }}</vxe-button
                                    >
                                    <vxe-button
                                        mode="text"
                                        status="danger"
                                        @click="removeRow(row)"
                                        v-if="row.level > 1"
                                        >删除</vxe-button
                                    >
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </el-col>
                    <el-col :span="16" style="border-left: 1px solid #d8d8d8">
                        <el-tag v-if="chooseChapter" style="margin: 15px 0"
                            >上传至 {{ chooseChapter }}</el-tag
                        >
                        <el-tag v-else style="margin: 15px 0" type="danger"
                            >请选择导入至哪一章节</el-tag
                        >
                        <el-form-item label="视频上传" v-if="chooseChapter">
                            <preview-upload
                                :showPreviewButton="true"
                                :showDownloadButton="false"
                                :showDeleteButton="true"
                                :multiple="false"
                                :isOnly="false"
                                acceptType=".mp4,.avi,.mpg,.flv,.wmv"
                                uploadUrl="/knowledgeFile/video/upload"
                                paramsName="file"
                                :videoType="1"
                                :accessoryList="filesArr"
                                @getValue="getAccessoryList"
                            ></preview-upload>
                        </el-form-item>

                        <el-form-item label="课件上传" v-if="chooseChapter">
                            <preview-upload
                                :showPreviewButton="true"
                                :showDownloadButton="false"
                                :showDeleteButton="true"
                                :multiple="false"
                                :isOnly="false"
                                acceptType=".ppt,.pptx"
                                uploadUrl="/knowledgeFile/video/upload"
                                paramsName="file"
                                :videoType="0"
                                :accessoryList="filesArr"
                                @getValue="getAccessoryList"
                            ></preview-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- <el-button v-if="filesArr.length > 0" type="primary" @click="importFn"
            >导入</el-button
        > -->

        <div style="text-align: center; margin-top: 10px">
            <el-button type="primary" @click="importFn">保存</el-button>
        </div>
    </div>
</template>
<script>
import PreviewUpload from '@/components/accessory/PreviewUploadVideo'
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      chooseChapter: '',
      uploadForm: {
        folderName: '',
        author: '',
        introduction: ''
      },
      currentRow: {},
      tableData: [],
      rules: {
        folderName: [
          { required: true, message: '请输入课程名称', trigger: 'change' }
        ],
        author: [
          { required: true, message: '请输入作者姓名', trigger: 'change' }
        ],
        introduction: [
          { required: true, message: '请输入课程简介', trigger: 'change' }
        ]
      },
      filesArr: []
    }
  },
  components: {
    PreviewUpload
  },
  watch: {
    'uploadForm.folderName'(newVal, oldVal) {
      if (this.tableData.length === 0) {
        this.tableData.push({
          chapterName: newVal,
          // id: Date.now(),
          chapter: Date.now(),
          parentId: null,
          level: 1,
          hasChildren: false,
          videoList: [],
          children: []
        })
      } else {
        this.tableData.map((item) => {
          if (item.parentId === null) {
            this.$set(item, 'chapterName', newVal)
          }
        })
      }
    }
  },
  mounted() {
    if (this.$route.query.from === 'editVideo') {
      this.getVideoDetail()
    }
  },
  methods: {
    getVideoDetail() {
      this.$http({
        url: '/knowledgeFile/video/detail',
        method: 'get',
        params: {
          id: this.$route.query.id
        }
      }).then(({ data }) => {
        console.log('data', data)
        if (data.code == 200) {
          this.uploadForm = data.data.course

          this.tableData = data.data.video && [data.data.video]
        }
      })
    },
    // 附件
    getAccessoryList(val) {
      this.filesArr = val
      const $table = this.$refs.tableRef
      const row = $table.getCurrentRecord()
      let fileIndex = row.videoList.findIndex(
        (item) => item.videoType === val[0].videoType
      )
      if (fileIndex === -1) {
        if (!row.videoList) {
          row.videoList = []
        }
        row.videoList = row.videoList.concat(val)
        // $table.reloadTreeExpand(row)
        this.$nextTick(() => {
          $table.setRowExpand([row], true)
        })
      } else {
        this.$message.error(
          '一个章/节下最多只存在一个视频文件和一个课件，上传新的视频需要先删除已有视频或课件'
        )
      }
    },
    deleteFile(currentRow, itemFile) {
      if (itemFile.id) {
        this.$http({
          url: '/knowledgeFile/file/delete',
          method: 'post',
          data: {
            id: itemFile.id
          }
        }).then(({ data }) => {
          console.log('data', data)
          if (data.code == 200) {
          }
        })
      }

      const $table = this.$refs.tableRef
      currentRow.videoList.forEach((item, index) => {
        if (item.fileName === itemFile.fileName) {
          currentRow.videoList.splice(index, 1)
        }
      })
      $table.reloadTreeExpand(currentRow)
      this.$nextTick(() => {
        $table.setRowExpand([currentRow], true)
      })
    },
    async insertRow(currRow) {
      const $table = this.$refs.tableRef
      // // 如果 null 则插入到目标节点顶部
      // // 如果 -1 则插入到目标节点底部
      // // 如果 row 则有插入到效的目标节点该行的位置
      const rid = Date.now()
      const number = currRow.children.length + 1
      const title = currRow.level === 1 ? '章' : '节'
      const record = {
        chapterName: `第${number}${title}`,
        // id: rid,
        chapter: rid,
        // parentId: currRow.id, // 需要指定父节点，自动插入该节点中
        level: currRow.level + 1,
        hasChildren: false,
        children: [],
        videoList: []
      }
      currRow.children = currRow.children.concat(record)
      $table.reloadTreeExpand(currRow)
      $table.remove({})
      // const { row: newRow } = await $table.insertAt(record, -1)
      // await $table.setTreeExpand(currRow, true) // 将父节点展开
      // await $table.setEditRow(newRow) // 插入子节点
      // this.$set(item, 'chapterName', newVal)
      // currRow.children.push(record)
      // this.tableData.push(record)
    },
    async removeRow(row) {
      if (row.videoList && row.videoList.length>0 ) {
        this.$message.error(
          '删除失败！该章节下存在文件，请删除文件后操作！'
        )
      } else {
        this.tableData[0].children.forEach((item, index) => {
        console.log(row,'rowwwwwwww',this.tableData)
        if (item.chapter === row.chapter) {
          this.tableData[0].children.splice(index, 1)
        } else {
          item.children && item.children.forEach((i, indexNum) => {
            console.log(row,'rowwwwwwww11111111111',this.tableData)
            if (i.chapter === row.chapter) {
              item.children.splice(indexNum, 1)
            }
          })
        }
      })
      const $table = this.$refs.tableRef
      await $table.remove(row)
      $table.reloadTreeExpand(row)
      }
      
      
    },
    currentChangeEvent({ row }) {
      console.log(row, '行选中事件')
      this.chooseChapter = row.chapterName
      this.currentRow = row
      // this.fileTable = row.videoList
    },
    importFn() {
      console.log('tree------', this.tableData)
      let url = ''
      const params = {
        ...this.uploadForm,
        profession: this.$route.query.profession,
        fileType: this.$route.query.fileType
      }
      if (this.$route.query.from === 'editVideo') {
        url = '/knowledgeFile/video/update'
        params.id = this.$route.query.id
      } else {
        url = '/knowledgeFile/video/save'
      }
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          this.$http({
            url,
            method: 'post',
            data: {
              course: params,
              video: {
                ...this.tableData[0]
              }
            }
          }).then(({ data }) => {
            console.log('data', data)
            if (data.code == 200) {
              this.$message.success('导入成功')
              this.$router.push('/knowledgeManage/originalFile')
            }
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
#contianer {
    width: 100%;
    height: 100%;
    background: #fff;
    padding: 50px;
    h2 {
        font-size: 20px;
        font-weight: 550;
    }
    .file_box {
        margin-top: 20px;
    }
}

</style>